<template>
  <div class="booksBox">
    <div class="header">
      <div>
        <el-button type="primary" @click="add" style="margin-left: 10px">{{
          $t("btn.add")
        }}</el-button>
      </div>

      <div class="search">
        <el-input
          style="width: 75%"
          v-model="content"
          @keyup.native.enter="search"
        ></el-input>
        <el-button type="primary" icon="el-icon-search" @click="search">{{
          $t("btn.search")
        }}</el-button>
        <el-button type="primary" @click="reset">{{
          $t("btn.reset")
        }}</el-button>
      </div>
    </div>

    <el-table style="width: 100%" :data="booksData">
      <el-table-column type="index" :label="$t('table.number')" width="100">
        <!-- <slot slot-scope="{ $index }">{{ $index + 1 }}</slot> -->
      </el-table-column>
      <el-table-column prop="title" :label="$t('table.bookName')">
      </el-table-column>
      <el-table-column :label="$t('table.picture')">
        <slot slot-scope="{ row }">
          <div class="demo-image__preview">
            <el-image
              style="width: 50px; height: 50px"
              :src="row.picture ? API + row.picture : ''"
              :preview-src-list="[row.picture ? API + row.picture : '']"
            >
              <div
                slot="error"
                class="image-slot"
                style="display: flex; justify-content: center"
              >
                <i class="el-icon-picture-outline"></i>
              </div>
              ></el-image
            >
          </div>
        </slot>
      </el-table-column>
      <el-table-column :label="$t('table.belongType')" prop="BooksType.name">
        <!-- <slot slot-scope="{ row }">
            {{ row.cate_id ? row.BooksType.name : "暂无分类" }}</slot
          > -->
      </el-table-column>
      <el-table-column :label="$t('table.operation')">
        <slot slot-scope="{ row }">
          <el-button
            type="warning"
            icon="el-icon-view"
            circle
            @click="particulars(row.content)"
          ></el-button>
          <el-button
            type="info"
            icon="el-icon-edit"
            circle
            @click="edit(row.id)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="del(row)"
          ></el-button>
        </slot>
      </el-table-column>
    </el-table>

    <div class="footer">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="count"
        :page-size="pageSize"
        @current-change="jump"
        :current-page.sync="pageNum"
      >
      </el-pagination>
    </div>
    <!-- 添加页面 -->
    <el-dialog
      title="添加"
      :visible.sync="dialogVisible1"
      width="60%"
      :before-close="handleClose1"
      :close-on-click-modal="false"
      v-if="dialogVisible1"
      destroy-on-close
    >
      <el-dialog
        width="80%"
        title="附件图片"
        :visible.sync="innerVisible"
        :show-close="false"
        :close-on-click-modal="false"
        :append-to-body="true"
        destroy-on-close
      >
        <el-upload
          :action="API + 'uploadPicture'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">从本地文件夹上传</div>
        </el-upload>
        <media
          :media-data="pictures"
          isShowOverspread
          @click="checkedImg"
        ></media>
        <div slot="footer" class="dialog-footer">
          <el-button @click="pictureCancel">取 消</el-button>
          <el-button
            type="primary"
            @click="confirmPicture"
            :disabled="!this.media.path"
            >确定</el-button
          >
        </div>
      </el-dialog>
      <el-form
        status-icon
        label-width="100px"
        class="demo-ruleForm"
        :model="addBookData"
        ref="form"
      >
        <el-form-item label="书名" prop="title">
          <el-input
            type="text"
            autocomplete="off"
            style="width: 70%"
            v-model="addBookData.title"
            name="addBookData.title"
          ></el-input>
        </el-form-item>

        <el-form-item label="所属分类" prop="bookType">
          <el-select
            placeholder="请选择书籍分类"
            v-model="addBookData.bookType"
            name="addBookData.bookType"
          >
            <el-option
              v-for="item in typeData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图">
          <div class="frame" @click="showPicture">
            <img
              v-if="checkedData.path"
              :src="checkedData.path"
              style="width: 100px; height: 100px"
            />
            <i v-else class="el-icon-plus" style="margin: 45px 0 0 45px"></i>
          </div>
        </el-form-item>
        {{ this.addBookData.content }}
        <el-form-item label="内容" prop="content">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px; overflow-y: hidden"
              v-model="addBookData.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
              @onBeforeUpload="onBeforeUpload"
            />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmAdd">添 加</el-button>
        <el-button @click="cancelAdd">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 编辑页面 -->
    <el-dialog
      title="编辑"
      :visible.sync="dialogVisible2"
      width="40%"
      :before-close="handleClose2"
      :close-on-click-modal="false"
    >
      <el-dialog
        width="80%"
        title="附件图片"
        :visible.sync="innerVisible2"
        :show-close="false"
        :close-on-click-modal="false"
        append-to-body
        destroy-on-close
      >
        <el-upload
          :action="API + 'uploadPicture'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">从本地文件夹上传</div>
        </el-upload>
        <media
          :mediaData="pictures"
          isShowOverspread
          @click="checkedEditImg"
        ></media>
        <div slot="footer" class="dialog-footer">
          <el-button @click="pictureCancel2">取 消</el-button>
          <el-button
            type="primary"
            @click="confirmPicture2"
            :disabled="!editMedia.path"
            >确定</el-button
          >
        </div>
      </el-dialog>
      <el-form
        status-icon
        label-width="100px"
        class="demo-ruleForm"
        :model="editBookData"
      >
        <el-form-item label="书名" prop="title">
          <el-input
            type="text"
            autocomplete="off"
            style="width: 70%"
            v-model="editBookData.title"
          ></el-input>
        </el-form-item>
        <el-form-item label="所属分类" prop="bookType">
          <el-select v-model="editBookData.bookType">
            <el-option
              v-for="item in typeData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="封面图">
          <div class="frame" @click="showPicture2">
            <img
              v-if="editBookData.uploadsUrl"
              :src="
                editCheckedData.path
                  ? editCheckedData.path
                  : API + editBookData.uploadsUrl
              "
              style="width: 100px; height: 100px"
            />
            <i v-else class="el-icon-plus" style="margin: 45px 0 0 45px"></i>
          </div>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editor"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px; overflow-y: hidden"
              v-model="editBookData.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="onCreated"
              @onBeforeUpload="onBeforeUpload"
            />
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
        <el-button @click="cancelEdit">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  
  <script>
import Vue from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import media from "@/components/Media";
import {
  getType,
  confirmAdd,
  edit,
  confirmEdit,
  del,
  paging,
  getAllPicture,
} from "@/api/";
let API = process.env.VUE_APP_API;
export default Vue.extend({
  components: {
    media,
    Editor,
    Toolbar,
  },
  data() {
    return {
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          uploadImage: {
            server: this.$API + "uploadPicture",
            fieldName: "file",
            maxFileSize: 2 * 1024 * 1024,
            maxNumberOfFiles: 3,
            allowedFileTypes: ["image/*"],
            customInsert: (res, insertFn) => {
              // res 即服务端的返回结果
              let url = this.$API + res;
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(url);
            },
          },
        },
      },
      mode: "default", // or 'simple'
      API,
      count: 0,
      pageSize: 5,
      booksData: [],
      content: "",
      addBookData: {
        title: "",
        content: "",
        bookType: "",
        uploadsUrl: "",
      },
      typeData: [],
      editBookData: {
        id: 0,
        title: "",
        content: "",
        bookType: "",
        uploadsUrl: "",
      },
      dialogVisible1: false,
      dialogVisible2: false,
      innerVisible: false,
      innerVisible2: false,
      pageNum: 1,
      pictures: [],
      checkIndex2: -1,
      checkPicture2: "",
      media: {},
      checkedData: {},
      editMedia: {},
      editCheckedData: {},
    };
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    onBeforeUpload(file) {
      return file;
    },

    onSuccess(file, res) {
      console.log("上传成功");
      console.log(`${file.name} 上传成功`, res);
    },
    // 上传错误，或者触发 timeout 超时
    onError(file, err, res) {
      console.log(`${file.name} 上传出错`, err, res);
    },
    // 编辑中选中的附件信息
    checkedEditImg(item) {
      this.editMedia = item;
    },
    // 添加中选中的附件信息
    checkedImg(item) {
      this.media = item;
    },
    async handleAvatarSuccess() {
      this.getAllMedia();
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 编辑中取消选择的附件按钮
    pictureCancel2() {
      this.innerVisible2 = false;
      this.editMedia = {};
    },
    // 编辑中确定选择的附件按钮
    confirmPicture2() {
      this.editCheckedData = this.editMedia;
      this.editBookData.uploadsUrl = this.editCheckedData.path
        ? this.editCheckedData.path.replace(this.API, "")
        : "";
      this.innerVisible2 = false;
      this.editMedia = {};
    },
    // 编辑页面展示所有附件
    async showPicture2() {
      this.innerVisible2 = true;
      this.getAllMedia();
    },
    // 添加中确定选择的附件按钮
    confirmPicture() {
      this.checkedData = this.media;
      this.innerVisible = false;
      this.media = {};
    },
    // 添加中取消选择的附件按钮
    pictureCancel() {
      this.innerVisible = false;
      this.media = {};
    },
    // 添加页面展示所有附件
    showPicture() {
      this.getAllMedia();
      this.innerVisible = true;
    },
    // 获取所有的图片附件
    async getAllMedia() {
      let { data } = await getAllPicture();
      let result = data.map((item) => {
        item.path = API + item.path;
        return item;
      });
      this.pictures = result;
    },
    // 重置搜索
    reset() {
      if (this.content != "") {
        this.content = "";
        this.pageNum = 1;
        this.paging();
      }
    },
    // 搜索
    async search() {
      if (!this.content.trim()) {
        this.$message({
          message: "搜索内容不能为空",
          type: "warning",
        });
        this.content = "";
        return;
      }
      this.pageNum = 1;
      this.paging();
    },
    // 获取所有书籍类型
    async getType() {
      let { data } = await getType();
      this.typeData = data;
    },
    // 查看详情
    particulars(content) {
      this.$alert(content, "详情", {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定",
        callback: (action) => {},
      });
    },
    // 添加页面
    add() {
      this.dialogVisible1 = true;
      this.getType();
    },
    handleClose1(done) {
      done();
      this.addBookData = {};
      this.checkedData = {};
    },
    // 添加操作
    async confirmAdd() {
      this.dialogVisible1 = false;
      let { data } = await confirmAdd({
        title: this.addBookData.title,
        content: this.addBookData.content,
        cateId: this.addBookData.bookType,
        picture: this.checkedData.path
          ? this.checkedData.path.replace(this.API, "")
          : "",
      });
      let { code, message } = data;
      if (code === 20000) {
        this.$message({
          message,
          type: "success",
        });
      } else {
        this.$message.error(message);
      }
      // this.paging(this.pageNum);
      this.paging();
      this.addBookData = {};
      this.checkedData = {};
    },
    // 取消添加
    cancelAdd() {
      this.dialogVisible1 = false;
      this.addBookData = {};
      this.checkedData = {};
    },
    // 编辑页面
    async edit(id) {
      this.dialogVisible2 = true;
      let { data } = await edit(id);
      this.getType();
      this.editBookData.id = data.id;
      this.editBookData.title = data.title;
      this.editBookData.content = data.content;
      this.editBookData.bookType = data.cate_id ? data.cate_id : "暂无分类";
      this.editBookData.uploadsUrl = data.picture;
    },
    handleClose2(done) {
      done();
      this.editCheckedData = {};
    },
    // 编辑操作
    async confirmEdit() {
      this.dialogVisible2 = false;
      let { data } = await confirmEdit(this.editBookData.id, {
        title: this.editBookData.title,
        content: this.editBookData.content,
        cateId: this.editBookData.bookType,
        picture: this.editBookData.uploadsUrl,
      });
      let { code, message } = data;
      if (code === 20000) {
        this.$message({
          message,
          type: "success",
        });
      } else {
        this.$message.error(message);
      }
      // this.paging(this.pageNum);
      this.paging();
      this.editCheckedData = {};
    },
    // 取消编辑
    cancelEdit() {
      this.dialogVisible2 = false;
      this.editCheckedData = {};
    },
    // 删除操作
    del(book) {
      let id = book.id;
      let title = book.title;
      this.$confirm(`你确定要删除《${title}》吗`, "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (this.booksData.length === 1) {
            this.pageNum -= 1;
          }
          let { data } = await del(id);
          let { code, message } = data;
          if (code === 20000) {
            this.$message({
              message,
              type: "success",
            });
          } else {
            this.$message.error(message);
          }

          // this.paging(this.pageNum);
          this.paging();
        })
        .catch(() => {});
    },
    // 封装一个分页跳转函数
    async paging() {
      let { data } = await paging(this.pageNum, this.pageSize, this.content);
      let { rows, totalCount } = data;
      this.booksData = rows;
      this.count = totalCount;
    },
    // 分页操作
    jump(...args) {
      this.pageNum = args[0];
      // this.paging(args[0]);
      this.paging();
    },
  },
  mounted() {
    // 挂载时默认调用一次
    this.paging();
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 组件销毁时，及时销毁编辑器
  },
});
</script>
  
  <style lang="scss" scoped>
.booksBox {
  width: 98%;
  min-height: 100%;
  // border: 1px solid #ccc;
  position: relative;

  .header {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;

    .search {
      width: 40%;
      display: flex;
      justify-content: space-between;
    }
  }
  .footer {
    position: absolute;
    width: 100%;
    bottom: 0;
    text-align: center;
  }

  .frame {
    width: 100px;
    height: 100px;
    border: 1px solid #ccc;
    border-radius: 4px;
  }
}
</style>